package com.maxd.service.common;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.respository.common.CommonJpaRepository;
import com.maxd.respository.common.CommonRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class CommonServiceImpl implements ICommonService {

    @Autowired
    private CommonJpaRepository appJpaRepository;

    @Autowired
    private CommonRepository commonRepository;

    @Override
    public Result findAll() {
        return ResultUtil.success(appJpaRepository.findAll());
    }

    @Override
    public Result saveBody(CommonInfo commonInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        commonInfo.setCreateAt(sdf.format(now));
        CommonInfo one = commonRepository.findOne(commonInfo.getType());
        if (one != null) {
            one.setValue(commonInfo.getValue());
            one.setCreateAt(commonInfo.getCreateAt());
            return ResultUtil.success(appJpaRepository.save(one));
        } else {
            return ResultUtil.success(appJpaRepository.save(commonInfo));
        }
    }


    @Override
    public Result findOne(long id) {
        return ResultUtil.success(appJpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(long id) {
        appJpaRepository.deleteById(id);
        return ResultUtil.success();
    }


    @Override
    @Transactional
    public Result updateBody(CommonInfo commonInfo) {
        CommonInfo commonInfo1 = appJpaRepository.findById(commonInfo.getId()).orElse(null);
        assert commonInfo1 != null;
        BeanUtils.copyProperties(commonInfo, commonInfo1);
        return ResultUtil.success();
    }

    @Override
    public Result findByType(Integer type) {
        return ResultUtil.success(commonRepository.findOne(type));
    }

    @Override
    public Result findByTypeAndCondition(String condition) {
        return ResultUtil.success(commonRepository.findByCondition(condition));
    }


}
